package com.haochang.chunkvod.controller.activity.hostess;

import java.util.ArrayList;
import java.util.List;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseTextView;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.utils.ToastUtils;
import com.haochang.chunkvod.model.hostess.HostessData;
import com.haochang.chunkvod.model.hostess.HostessInfo;
import com.haochang.chunkvod.tools.vod.log.Logger;
import com.haochang.chunkvod.tools.vod.other.DipPxConversion;
import com.haochang.chunkvod.view.vod.ScrollView.CustomHorizontalScrollView;
import com.haochang.chunkvod.view.vod.ScrollView.CustomScrollView;
import com.haochang.chunkvod.view.vod.popupWindow.VodPopWindow;
import com.haochang.chunkvod.view.vod.title.TitleView;

import android.os.Bundle;
import android.support.v4.view.GestureDetectorCompat;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;

/**
 * @author Yangjie
 *         className ReserveActivity
 *         created at  2016/8/23  18:08
 *         咨客 可用房间
 */
public class UsableRoomActivity extends BaseActivity
{
	private TitleView titleView;
	private CustomHorizontalScrollView horizontalScr_title;
	private CustomHorizontalScrollView horizontalScr_content;
	private CustomScrollView scrollView;
	private TableLayout tablelayout_time;
	private TableLayout tablelayout_data;
	private LinearLayout linear_title;

	private List<HostessInfo> listData;
	private HostessData hostessData;
	private boolean firstSuccess = false;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		gestureDetectorCompat = new GestureDetectorCompat(UsableRoomActivity.this, new MySimpleOnGestureListener());
	}

	@Override
	public void receiveParam()
	{
	}

	@Override
	public void initData()
	{
		hostessData = new HostessData(this);
	}

	@Override
	public void onResume()
	{
		super.onResume();
		if (!firstSuccess)
			requestUsableRoomList(true);
	}

	@Override
	public void initViews()
	{
		setContentView(R.layout.activity_usable_room);
		linear_title = (LinearLayout) findViewById(R.id.linear_title);
		tablelayout_time = (TableLayout) findViewById(R.id.tablelayout_time);
		tablelayout_data = (TableLayout) findViewById(R.id.tablelayout_data);
		horizontalScr_title = (CustomHorizontalScrollView) findViewById(R.id.horizontalScr_title);
		horizontalScr_content = (CustomHorizontalScrollView) findViewById(R.id.horizontalScr_content);
		scrollView = (CustomScrollView) findViewById(R.id.scrollView);

		horizontalScr_title.setScrollView(horizontalScr_content);
		horizontalScr_content.setScrollView(horizontalScr_title);
		titleView = (TitleView) findViewById(R.id.titleView);
		titleView.setTitle(R.string.usableApartment).setTitleOnClickListener(new TitleView.ITitleOnClickListener()
		{
			@Override
			public void onBackClick()
			{
				finish();
				animRightToLeft();
			}

			@Override
			public void onDoneClick()
			{
				List<String> list = new ArrayList<String>();
				list.add("回到首页");
				list.add("修改密码");
				list.add("退出登录");
				int location[] = new int[2];
				ImageView img = (ImageView) titleView.findViewById(R.id.img_operates);
				img.getLocationOnScreen(location);
				int x = location[0];
				final VodPopWindow pop = new VodPopWindow(UsableRoomActivity.this, list);
				pop.showPopupWindow(titleView, x);
				pop.setPopWindowListListener(new VodPopWindow.OnPopWindowListListener()
				{
					@Override
					public void onSelectItem(int position)
					{
						switch (position)
						{
						case 0:
							backToHome();
							break;
						case 1:
							goToPasswordModify();
							break;
						case 2:
							loginOut();
							break;

						default:
							break;
						}
					}
				});
			}
		});
	}

	private void initUsableRoomList(SparseArray<List<HostessInfo>> list)
	{
		//如果已添加则先清除
		if (linear_title.getChildCount() >= 2)
		{
			linear_title.removeViewAt(0);
		}
		//以下添加左上 时间
		final ViewGroup viewGroup = null;
		View v = getLayoutInflater().inflate(R.layout.item_usable_room_data, viewGroup, false);
		RelativeLayout rela_root = (RelativeLayout) v.findViewById(R.id.rela_root);
		BaseTextView tv_content = (BaseTextView) v.findViewById(R.id.tv_content);
		tv_content.setText(R.string.time_zoom);
		tv_content.setBackgroundColor(getResources().getColor(R.color.color_f9f9f9));
		tv_content.setTextColor(getResources().getColor(R.color.color_737373));
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DipPxConversion.dip2px(this, 70) + 1, LinearLayout.LayoutParams.MATCH_PARENT);
		LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(DipPxConversion.dip2px(this, 69), LinearLayout.LayoutParams.MATCH_PARENT);
		rela_root.setLayoutParams(params);
		tv_content.setLayoutParams(params2);
		linear_title.addView(v, 0);
		//以下添加中间内容
		listData = new ArrayList<HostessInfo>();
		tablelayout_data.removeAllViews();
		tablelayout_time.removeAllViews();
		horizontalScr_title.removeAllViews();
		if (list == null || list.size() <= 0 || list.get(0) == null)
		{
			ToastUtils.showText(UsableRoomActivity.this, "暂无数据");
			return;
		}
		int lenthRow = list.size();//有多少行
		int lenthColumn = list.get(0).size();//有多少列
		Logger.e("行:" + lenthRow);
		Logger.e("列:" + lenthColumn);
		for (int i = 0; i < lenthRow; i++)
		{//行
			for (int j = 0; j < lenthColumn; j++)
			{//列
				List<HostessInfo> list1 = list.get(i);
				HostessInfo info = list1.get(j);
				if (i == 0)
				{
					info.setContent(info.getContent());
					info.setUsableNum(info.getUsableNum());
					info.setTimeZoom(info.getTimeZoom());
					listData.add(info);
				} else
				{
					info.setUsableNum(info.getUsableNum());
					info.setTimeZoom(info.getTimeZoom());
					listData.add(info);
				}
				if (j == 0)
				{
					tablelayout_time.addView(getTimeZoomRow(i * lenthColumn));//添加时间轴
				}
			}
			tablelayout_data.addView(getDataRow(i, lenthColumn));//一行一行添加数据
		}
		horizontalScr_title.addView(getHead(lenthColumn));//添加标题  前n列
	}

	/**
	 * 获取剩余房间信息
	 */
	public void requestUsableRoomList(boolean isLoading)
	{
		hostessData.requestUsableRoomList(isLoading, new HostessData.ResultResponseMultipleList<HostessInfo>()
		{
			@Override
			public void onRequestSuccess(SparseArray<List<HostessInfo>> list, boolean clear)
			{
				Logger.e("可用房间success:");
				firstSuccess = true;
				if (list != null)
				{
					initUsableRoomList(list);
				}
			}

			@Override
			public void onFail(int errno, String errMsg)
			{
				ToastUtils.showText(UsableRoomActivity.this, "请求失败");
			}
		});
	}

	/**
	 * 初始化时间轴
	 *
	 * @param rowNum 行号
	 * @return TableRow返回一行tableRow
	 */
	public TableRow getTimeZoomRow(int rowNum)
	{
		TableRow tableRow = new TableRow(this);
		final ViewGroup viewGroup = null;
		View v = this.getLayoutInflater().inflate(R.layout.item_usable_room_timezoom, viewGroup, false);
		BaseTextView id_text = (BaseTextView) v.findViewById(R.id.tv_content);
		id_text.setText(listData.get(rowNum).getTimeZoom());
		tableRow.addView(v);
		return tableRow;
	}

	/**
	 * 初始化数据
	 *
	 * @param rowNum 第几行 totalColumns 总列数
	 * @return TableRow
	 */
	public TableRow getDataRow(int rowNum, int totalColumns)
	{
		TableRow tableRow = new TableRow(this);
		LinearLayout linearLayout = new LinearLayout(this);
		for (int i = 0; i < totalColumns; i++)
		{
			HostessInfo info = listData.get(rowNum * totalColumns + i);
			final ViewGroup viewGroup = null;
			View view = this.getLayoutInflater().inflate(R.layout.item_usable_room_data, viewGroup, false);
			BaseTextView tv_content = (BaseTextView) view.findViewById(R.id.tv_content);
			tv_content.setText(String.valueOf((TextUtils.isEmpty(info.getUsableNum()) ? "0" : info.getUsableNum()) + " ( "
					+ (TextUtils.isEmpty(info.getReserveNum()) ? "0" : info.getReserveNum()) + " )"));
			try
			{
				if (Integer.parseInt(info.getUsableNum()) <= 0)
				{
					tv_content.setTextColor(getResources().getColor(R.color.color_f04e39));
				} else
				{
					tv_content.setTextColor(getResources().getColor(R.color.color_282828));
				}
			} catch (Exception e)
			{
				tv_content.setTextColor(getResources().getColor(R.color.color_282828));
			}
			linearLayout.addView(view);
		}
		tableRow.addView(linearLayout);
		return tableRow;
	}

	public View getHead(int lineCount)
	{
		LinearLayout linearLayout = new LinearLayout(this);
		for (int i = 0; i < lineCount; i++)
		{
			final ViewGroup viewGroup = null;
			View view = this.getLayoutInflater().inflate(R.layout.item_usable_room_data, viewGroup, false);
			BaseTextView tv_content = (BaseTextView) view.findViewById(R.id.tv_content);
			tv_content.setText(listData.get(i).getContent());
			tv_content.setTextColor(getResources().getColor(R.color.color_737373));
			tv_content.setBackgroundColor(getResources().getColor(R.color.color_f9f9f9));
			linearLayout.addView(view);
		}
		return linearLayout;
	}

	GestureDetectorCompat gestureDetectorCompat;
	float initX, initY;
	float currentX, currentY;
	float currentScrollX, currentScrollY;
	float lastX, lastY;

	@Override
	public boolean onTouchEvent(MotionEvent event)

	{
		switch (event.getAction())
		{
		case MotionEvent.ACTION_DOWN:
			currentScrollX = horizontalScr_content.getScrollX();
			currentScrollY = scrollView.getScrollY();
			initX = event.getX();
			initY = event.getY();
			lastX = event.getX();
			lastY = event.getY();
			Logger.e("ACTION_DOWN: ");
			break;
		case MotionEvent.ACTION_MOVE:
			currentX = event.getX();
			currentY = event.getY();
			Logger.e("onScroll: " + "e1:" + (lastX + "  " + -currentX) + "  " + horizontalScr_content.getScrollX());

			if (Math.abs(lastX - currentX) > 30)
			{
				//				lastMotionEvent = event;
				horizontalScr_content.scrollTo((int) (currentScrollX + (initX - currentX)), 0);
			}
			if (Math.abs(lastY - currentY) > 30)
			{
				//				lastMotionEvent = event;
				scrollView.scrollTo(0, (int) (currentScrollY + (initY - currentY)));
			}
			break;
		}
		//		return  gestureDetectorCompat.onTouchEvent(event);
		return super.onTouchEvent(event);
	}

	class MySimpleOnGestureListener extends SimpleOnGestureListener
	{
		@Override
		public boolean onDown(MotionEvent event)
		{
			currentScrollX = horizontalScr_content.getScrollX();
			currentScrollY = scrollView.getScrollY();
			Logger.e("onDown: " + event.toString());
			return true;
		}

		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY)
		{
			Logger.e("onFling: " + e1.getX() + "    " + e2.getY());
			//			initX = e1.getX();
			//			initY = e1.getY();
			//			currentX = e2.getX();
			//			currentY = e2.getY();
			horizontalScr_content.scrollTo((int) (currentScrollX + (e1.getX() - e2.getX())), 0);
			return true;
		}

		@Override
		public boolean onDoubleTap(MotionEvent e)
		{
			Logger.e("onDoubleTap: ");
			return super.onDoubleTap(e);
		}

		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY)
		{
			Logger.e("onScroll: " + "e1:" + e1.getX() + "  " + e1.getY() + "    e2:" + e2.getX() + "  " + e2.getY() + "   horizontalScr_content.getScrollX:"
					+ horizontalScr_content.getScrollX());
			initX = e1.getX();
			initY = e1.getY();
			currentX = e2.getX();
			currentY = e2.getY();
			horizontalScr_content.scrollTo((int) (currentScrollX + (initX - currentX)), 0);
			scrollView.scrollTo(0, (int) (currentScrollY + (initY - currentY)));
			return super.onScroll(e1, e2, distanceX, distanceY);
		}

		@Override
		public void onLongPress(MotionEvent e)
		{
			Logger.e("onLongPress: ");
			super.onLongPress(e);
		}
	}
}
